import os
import pysvn

from damn import FileReference

from damn.provider import BaseProvider
class SVNProvider(BaseProvider):
  handled_types = ["svn://", "https://"]
  
  def __init__(self):
    self.client = pysvn.Client()
    self.client.callback_ssl_server_trust_prompt = SVNProvider.__ssl_server_trust_prompt
   
  @staticmethod  
  def __ssl_server_trust_prompt( trust_dict ):
    return True, trust_dict['failures'], True
  
  @staticmethod
  def __notify(cb):  
    def notify(d):
      d['path'] = os.path.abspath(d['path'])
      if d['action']== pysvn.wc_notify_action.update_add:
        if d['kind'] == pysvn.node_kind.file:
          fileRef = FileReference(d['path'])
          cb.addFile(fileRef)  
      elif d['action']== pysvn.wc_notify_action.update_delete:
        if d['kind'] == pysvn.node_kind.file:
          cb.deleteFile(d['path']) 
        elif d['kind'] == pysvn.node_kind.dir:
          cb.deleteDir(d['path']) 
      elif d['action']== pysvn.wc_notify_action.update_update:
        if d['kind'] == pysvn.node_kind.file: 
          fileRef = FileReference(d['path'])
          cb.addFile(fileRef) 
      else:
        print(d['action'], d['path']) 
    return notify

  def checkout(self, sourceURI, targetURI, aCallBack):
    self.client.callback_notify = SVNProvider.__notify(aCallBack)
    rev = self.client.checkout(sourceURI, targetURI)
    return True
    
  def update(self, sourceURI, targetURI, aCallBack):
    self.client.callback_notify = SVNProvider.__notify(aCallBack)
    rev = self.client.update(targetURI)
    return True
    
  def scan(self, sourceURI, targetURI, aCallBack):
    def Walk(path): 
      for top, dirs, files in os.walk(path):
        #Excludes
        if ".svn" in dirs:
          dirs.remove(".svn")
        for f in files:
          fileRef = FileReference(os.path.join(top, f))
          try:
            p, info = self.client.info2(os.path.join(top, f))[0]
            fileRef.user = info['last_changed_author']
          except pysvn.ClientError as e:
            print e
          aCallBack.updateFile(fileRef)
       
    Walk(targetURI)
    return True






